package com.acoreful.acf2java.admin.modules.auth.service.impl;

import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.acoreful.acf2java.admin.modules.auth.service.CaptchaService;
import com.acoreful.acf2java.commons.redis.RedisKeys;
import com.acoreful.acf2java.commons.redis.RedisOps;
import com.google.code.kaptcha.Producer;

@Service
public class CaptchaServiceImpl implements CaptchaService {

private static final Logger logger = LoggerFactory.getLogger(CaptchaServiceImpl.class);
    
    private static final long TIMEOUT_IN_SECONDS = 120L;
    
    @Autowired
    private Producer producer;
    
    @Autowired
    private RedisOps redisOps;
    
    public long timeoutInSeconds = TIMEOUT_IN_SECONDS;
    
    public void setTimeoutInSeconds(long timeoutInSeconds) {
        this.timeoutInSeconds = timeoutInSeconds;
    }

    @Override
    public BufferedImage createImage(String captchaToken) {
        String captchaText = producer.createText();
        logger.debug("captchaToken {} -> catpcha {}", captchaToken, captchaText);
        redisOps.getValueOps().set(RedisKeys.adminCaptcha(captchaToken), captchaText, timeoutInSeconds, TimeUnit.SECONDS);
        return producer.createImage(captchaText);
    }

    @Override
    public boolean validate(String token, String captchaText) {
        return StringUtils.equals(redisOps.getValueOps().get(RedisKeys.adminCaptcha(token)), captchaText);
    }

}
